﻿using fuzhu;
using LH.Models.APAR;
using U8COWeb;
using XXX.Bo;
using XXX.Models;

namespace Yonyou.U8.BO
{
    //取glmodel，为来源参照
    public class APClosebillVM : Api_CloseBill
    {
        //当前的数据库连接字符串
        public string conStr { get; set; }
        public static string cDatabase = "";

        public bool exist_SettleStyle(string csscode, ref string errMsg)
        {
            if (string.IsNullOrEmpty(csscode))
            {
                errMsg += "结算方式未输入:";
                return false;
            }

            string f1 = "select count(1) from   SettleStyle where cSSCode='" + csscode + "' and convert(int,isnull(bSSEnd,0))=1 ";
            int icount = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(f1, conStr));
            if (icount <= 0)
            {
                errMsg += "末级结算方式不存在:" + csscode;
                return false;
            }
            else
            {
                return true;
            }
        }
        public  RetModel2 AddFuKuan()
        {


            try
            { 
                string sql = "";

                //检查QID
                if (string.IsNullOrWhiteSpace(cVouchID))
                {
                    throw new Exception("付款单号不能为空");
                }

                 
                string errMsg = "";
                if (!exist_SettleStyle(cSSCode, ref errMsg))
                {
                    throw new Exception(errMsg);
                }

                sql = string.Format("select iid from ap_closebill where cVouchID='{0}'", cVouchID);
                Object oid = DbHelper2.ExecuteScalar(sql, conStr);
                if (oid != null)
                {
                   throw new Exception("该任务已执行"); 
                }
                string benbi;
                //账套是001的，本币是港币HKD
                sql = string.Format("select cexch_name from foreigncurrency where iotherused=-1");
                benbi = DbHelper.GetDbString(DbHelper2.ExecuteScalar(sql, conStr));

                RetModel2 retModel = new RetModel2();
               GLaccvouchVM gLaccvouchVM = new GLaccvouchVM();
                gLaccvouchVM.conStr  = conStr;
                LH.Model.APAR.AP_CloseBill.Head rdHead = new LH.Model.APAR.AP_CloseBill.Head();

                rdHead.cVouchType = "49";//单据类型
                rdHead.cFlag = "AP";
                rdHead.dVouchDate = DbHelper.GetDbDate(dVouchDate).ToString("yyyy-MM-dd");
                //判断单位是否存在
                if ( !gLaccvouchVM.exist_vendor(cDwCode, ref errMsg))
                  {
                    throw new Exception(errMsg);
                   }
               
                rdHead.cDwCode = cDwCode;
                

                rdHead.cSSCode =  cSSCode; //结算方式，默认转账
                rdHead.iPeriod = DbHelper.GetDbDate(dVouchDate).Month.ToString();
                //科目辅助核算判断
                int b_dep_fzhs = 0;
                int b_person_fzhs = 0;
                int b_cus_fzhs = 0;
                int b_vendor_fzhs = 0;
                int b_fitem_fzhs = 0;
                string c_cass_item = "";
                string c_cexch_name = "";  //凭证币种
                int b_bend = 0;
                int b_bclose = 0;
                int b_bcDefine1 = 0;
                int b_bcDefine2 = 0;
                int b_bcDefine3 = 0;
                int b_bcDefine4 = 0;
                int b_bcDefine5 = 0;
                int b_bcDefine6 = 0;
                int b_bcDefine7 = 0;
                int b_bcDefine8 = 0;
                int b_bcDefine9 = 0;
                int b_bcDefine10 = 0;
                int b_bcDefine11 = 0;
                int b_bcDefine12 = 0;
                int b_bcDefine13 = 0;
                int b_bcDefine14 = 0;
                int b_bcDefine15 = 0;
                int b_bcDefine16 = 0;
                string c_cother = "";
                if (!string.IsNullOrWhiteSpace(cCode))
                {
                    //if (!gLaccvouchVM.exist_code(cCode, DbHelper.GetDbDate(dVouchDate).Year, ref errMsg))
                    //{
                    //    throw new Exception(errMsg);
                    //} 
                    bool b3 = gLaccvouchVM.getFuZhuHeSuan(cCode, DbHelper.GetDbDate(dVouchDate).Year, ref b_dep_fzhs, ref b_person_fzhs, ref b_cus_fzhs,
                                  ref b_vendor_fzhs, ref b_fitem_fzhs, ref c_cass_item, ref c_cexch_name, ref b_bend, ref b_bclose, ref b_bcDefine1,
                                  ref b_bcDefine2, ref b_bcDefine3, ref b_bcDefine4, ref b_bcDefine5, ref b_bcDefine6, ref b_bcDefine7,
                                  ref b_bcDefine8, ref b_bcDefine9, ref b_bcDefine10, ref b_bcDefine11, ref b_bcDefine12, ref b_bcDefine13,
                                  ref b_bcDefine14, ref b_bcDefine15, ref b_bcDefine16, ref c_cother, ref errMsg);

                    if (!b3)
                    {
                        throw new Exception(errMsg);
                    }

                    rdHead.cCode = cCode;
                }

                rdHead.cexch_name = cexch_name;
                rdHead.iExchRate = iExchRate;
                rdHead.iAmount_f = iAmount_f;
                rdHead.iAmount = iAmount;
                rdHead.iRAmount_f = iAmount_f;
                rdHead.iRAmount = iAmount;
                rdHead.cTypeName = "付款单";
                //rdHead.cCheckMan = "demo";
                rdHead.cOperator =  cMaker;
                rdHead.cVouchID = cVouchID;
                rdHead.VT_ID = "8053";
                //rdHead.cLink = "P00000000018";
                rdHead.bStartFlag = "False";
                rdHead.cDigest = cDigest;
                rdHead.cDefine11 = cDigest;
                rdHead.iPayType = "0";

                if (string.IsNullOrEmpty(cexch_name))
                {
                    throw new Exception("表头币种不能为空");
                }
                if (!string.IsNullOrEmpty(c_cother) && c_cother == "AP")
                {
                    throw new Exception("表头科目不能是应付受控科目 " + rdHead.cCode);
                }

                //如果币种有外币核算，这边输入的不一样进行提示
                if (c_cexch_name != "" && cexch_name != c_cexch_name)
                {
                    throw new Exception("表头科目" + rdHead.cCode + "有外币核算，请输入外币:" + c_cexch_name);
                }


                //没有外币核算，输入的币种必须和本币一致
                if (c_cexch_name == "" && cexch_name != benbi)
                {
                    throw new Exception("科目" + rdHead.cCode + "没有外币核算，请输入本位币币:" + benbi);
                }
                //如果有外币核算，汇率没有输入，提示输入汇率
                if (c_cexch_name != "" && (string.IsNullOrEmpty(iExchRate) || iExchRate == "0"))
                {
                    throw new Exception("表头汇率不能为空或者0");
                }
                if (string.IsNullOrEmpty(iAmount) || iAmount == "0")
                {
                    throw new Exception("表头金额不能为空");
                }
                if (string.IsNullOrEmpty(iAmount_f) || iAmount_f == "0")
                {
                    throw new Exception("表头外币金额不能为空");
                }
                //如果没有外币核算，汇率输入不是1，或者外币金额不等于本币金额，提示输入错误
                //if (c_cexch_name == "" && (iExchRate != "1" || iAmount != iAmount_f))
                //{
                //    throw new Exception("表头外币金额不等于本币金额");
                //}

                //不管有没有辅助核算，单据都进行赋值
                if (b_vendor_fzhs == 1)
                {
                    if (string.IsNullOrWhiteSpace(cDwCode))
                    {
                        throw new Exception("表头有供应商核算，表头供应商不能为空");
                    }


                }
                //判断单位是否存在
                if (!string.IsNullOrEmpty(cDwCode) && !gLaccvouchVM.exist_vendor(cDwCode, ref errMsg))
                {
                    throw new Exception(errMsg);
                }
                rdHead.cDwCode = cDwCode;

                //有部门核算，没有输入，进行提示
                if (b_dep_fzhs == 1)
                {
                    if (string.IsNullOrWhiteSpace(cDeptCode))
                    {
                        throw new Exception("表头有部门核算，部门不能为空");
                    }
                }
                //检查部门输入是否正确
                if (!string.IsNullOrEmpty(cDeptCode) && !gLaccvouchVM.exist_dept(cDeptCode, ref errMsg))
                {
                    throw new Exception(errMsg);
                }
                rdHead.cDeptCode = cDeptCode;
                //有人员核算，没有输入，进行提示
                if (b_person_fzhs == 1)
                {
                    if (string.IsNullOrWhiteSpace(cPerson))
                    {
                        throw new Exception("表头有人员核算，业务员不能为空");
                    }

                }
                if (!string.IsNullOrEmpty(cPerson) && !gLaccvouchVM.exist_person(cPerson, ref errMsg))
                {
                    throw new Exception(errMsg);
                }
                rdHead.cPerson = cPerson;
                //有项目核算，没有输入，进行提示
                if (b_fitem_fzhs == 1)
                {
                    if (string.IsNullOrWhiteSpace(cItemCode))
                    {
                        throw new Exception("表头有项目核算，表头项目不能为空");
                    }
                    //没有检查项目是否正确

                }
                rdHead.cItem_Class = cItem_Class;
                rdHead.cItemCode = cItemCode;
                rdHead.IsWfControlled = "False";
                rdHead.iAmount_s = "0";
                //rdHead.cPayType = "货款";

                List<LH.Model.APAR.AP_CloseBill.Body> bodies = new List<LH.Model.APAR.AP_CloseBill.Body>();



                LH.Model.APAR.AP_CloseBill.Body body = new LH.Model.APAR.AP_CloseBill.Body();


                body.bPrePay = "False";
                body.iType = "0";
                body.cType = "应付款";
                body.iAmt_f = iAmount_f;
                body.iAmt = iAmount;
                body.iRAmt_f = iAmount_f;
                body.iRAmt = iAmount;
                if (!string.IsNullOrWhiteSpace(cKM))
                {
                    b_dep_fzhs = 0;
                    b_person_fzhs = 0;
                    b_cus_fzhs = 0;
                    b_vendor_fzhs = 0;
                    b_fitem_fzhs = 0;
                    c_cass_item = "";
                    c_cexch_name = "";  //凭证币种
                    b_bend = 0;
                    b_bclose = 0;
                    b_bcDefine1 = 0;
                    b_bcDefine2 = 0;
                    b_bcDefine3 = 0;
                    b_bcDefine4 = 0;
                    b_bcDefine5 = 0;
                    b_bcDefine6 = 0;
                    b_bcDefine7 = 0;
                    b_bcDefine8 = 0;
                    b_bcDefine9 = 0;
                    b_bcDefine10 = 0;
                    b_bcDefine11 = 0;
                    b_bcDefine12 = 0;
                    b_bcDefine13 = 0;
                    b_bcDefine14 = 0;
                    b_bcDefine15 = 0;
                    b_bcDefine16 = 0;
                    c_cother = "";

                    bool b1 = gLaccvouchVM.getFuZhuHeSuan(cKM, DbHelper.GetDbDate(dVouchDate).Year, ref b_dep_fzhs, ref b_person_fzhs, ref b_cus_fzhs,
                             ref b_vendor_fzhs, ref b_fitem_fzhs, ref c_cass_item, ref c_cexch_name, ref b_bend, ref b_bclose, ref b_bcDefine1,
                             ref b_bcDefine2, ref b_bcDefine3, ref b_bcDefine4, ref b_bcDefine5, ref b_bcDefine6, ref b_bcDefine7,
                             ref b_bcDefine8, ref b_bcDefine9, ref b_bcDefine10, ref b_bcDefine11, ref b_bcDefine12, ref b_bcDefine13,
                             ref b_bcDefine14, ref b_bcDefine15, ref b_bcDefine16, ref c_cother, ref errMsg);
                    if (!b1)
                    {
                        throw new Exception(errMsg);
                    }

                    body.cKm = cKM;
                }
                if (string.IsNullOrEmpty(c_cother) || c_cother != "AP")
                {
                    throw new Exception("表体科目不是应付受控科目：" + cKM);
                }
                
                body.cCusVen = cDwCode ;
                body.cDepCode = cDeptCode;
                body.iAmt_s = "0";
                body.iRAmt_s = "0";

                body.editprop = "A";

                bodies.Add(body);


                LH.Model.APAR.AP_CloseBill entity = new LH.Model.APAR.AP_CloseBill(rdHead, bodies);

                string cerr, cid, ccode;
                string xmlconfig = XmlOperation.GetAccountConfigXML(accid, rdHead.dVouchDate);
                if (!APCloseBillDALCO.AddAPCloseBill(entity, xmlconfig, out cerr, out cid, out ccode))
                {
                    throw new Exception(cerr);
                }
               else
                {
                    //如果执行成功了，检查单据号是不是传入的单据号（单据编码选项是 相同的就自动生成）。 如果不是，也删除
                    if (ccode != rdHead.cVouchID)
                    {
                        //单据编码选项判断
                        sql = string.Format(@"Select  bRepeatReDo  From VoucherNumber Where CardNumber='付款单'");
                        int iRepeat = DbHelper.GetDbInt(SqlsugarHelper.Instance.Ado.GetScalar(sql));
                        if (iRepeat == 1)
                        {
                            string cerr2 = "";
                            APCloseBillDALCO.OperateAPCloseBill(cid, xmlconfig,"unverify,delete" ,out cerr2);
                            return DBService.ReOKObject("之前单据已生成，重复");
                        }
                    }
                }
                return DBService.ReOKObject(ccode);


            }
            catch (Exception ex)
            {
                //             string SQL = string.Format(@"update  formmain_0175  set  field0026 ='{1}' where field0003='{0}'
                //", shouKuan.cCode,ex.Message);
                //                DbHelper2.ExecuteNonQuery(SQL, CanShu.conStrOA);
                return DBService.ReErrObject(ex.Message);
            }

        }

    }
}
